<?php

namespace App\Repositories;

use App\Models\MemberPark;
use App\Models\Park;
use Exception;

class ParkRepository
{

    public function getList($filter = [], $pageNum = 2, $pageSize = 10): array
    {
        $res = Park::query()
            ->when(!empty($filter['keywords']), function ($query) use ($filter) {
                return $query->where("title", "like", "%{$filter['keywords']}%");
            })
            ->orderBy("id", "desc")
            ->paginate($pageSize, ["*"], null, $pageNum)
            ->toArray();
        return filterPaginateData($res);
    }

    public function getOne($id = null)
    {
        return Park::query()->where("id", $id)->first();
    }

    public function saveOrUpdate($data = [], $id = 0)
    {
        if (!empty($data['id']))
            unset($data['id']);

        if (intval($id)) {
            Park::where("id", $id)->update($data);
            return $id;
        } else {
            $res = Park::create($data);
            return $res['id'] ?? "";
        }
    }

    /**
     * 删除
     * @param null $id
     */
    public function deletePark($id = null)
    {
        if (!intval($id))
            return retFail("参数错误");

        Park::where(['id' => intval($id)])->delete();

        return retSuc([], "删除成功");
    }

    public function getOptions($filter = [])
    {
        return Park::query()
            ->where(['status' => 1])
            ->orderBy("id", "desc")
            ->get(['id', 'title'])
            ->toArray();
    }

    /**
     * 更新会员关联的园区
     * @param $uid
     * @param array $parkIds
     * @throws Exception
     */
    public function updateMemberMapping(int $uid, $parkIds = [])
    {
        if (!$uid)
            throw new Exception("会员不存在");

        MemberPark::query()->where(['uid' => intval($uid)])->delete();

        $data = [];
        foreach ($parkIds as $k => $parkId) {
            $data[] = [
                'uid' => $uid,
                'park_id' => $parkId,
                'create_time' => time(),
                'update_time' => time(),
            ];
        }

        MemberPark::insert($data);

        return true;
    }

    public function getParks()
    {
        return Park::query()->where('status', 1)->get(['id', 'title']);
    }
}
